import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import {
  Spin,
  Tooltip,
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Badge,
  Divider,
  Steps,
  Radio,
  Tag,
} from 'antd';
import moment from 'moment';
import router from 'umi/router';
import XLSX from '../../../assets/xlsx.min';
// import * as XLSX from 'xlsx-style';

import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import styles from './Test.less';

const listernerable = false;
const FormItem = Form.Item;
const { Step } = Steps;
const { TextArea } = Input;
const { Option } = Select;
const RadioGroup = Radio.Group;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');
const statusMap = ['default', 'processing', 'success', 'error'];

/* eslint react/no-multi-comp:0 */
@connect(({ aiwatch, loading }) => ({
  aiwatch,
  loading: loading.models.modelAIwatch,
}))
@Form.create()
class TwoFundPosition extends PureComponent {
  state = {
    filterData: [],
    expandForm: false, // 查询菜单栏 是否显示
    listLoading: false,
    formValues: {
      method: 'GetList',
      page: 1,
      pagesize: 200,
      type: 3,
      name: '',
    }, // 查询菜单栏   查询参数
    modalVisible: false,
    updateModalVisible: false,
    selectedRows: [],
    stepFormValues: {},
  };

  columns = [
    {
      title: 'BID做多',
      dataIndex: 'bidcall',
      render: text => <span>{text || '-'}</span>,
    },
    {
      title: 'BID做空',
      dataIndex: 'bidput',
      render: text => <span>{text || '-'}</span>,
    },
    {
      title: 'ETF做多',
      dataIndex: 'etfcall',
      render: text => <span>{text || '-'}</span>,
    },
    {
      title: 'ETF做空',
      dataIndex: 'etfput',
      render: text => <span>{text || '-'}</span>,
    },
  ];

  // 默认加载数据-起始方法
  render() {
    function formatdata(res) {
      if (res.code == 1 && typeof res.data !== 'number') {
        res.data.bidcall = res.data.bidcall ? res.data.bidcall : [];
        res.data.bidput = res.data.bidput ? res.data.bidput : [];
        res.data.etfcall = res.data.etfcall ? res.data.etfcall : [];
        res.data.etfput = res.data.etfput ? res.data.etfput : [];

        const maxl = Math.max.apply(null, [
          res.data.bidcall.length,
          res.data.bidput.length,
          res.data.etfcall.length,
          res.data.etfput.length,
        ]);
        const tabdata = [];
        for (let i = 0; i < maxl; i++) {
          tabdata.push({
            bidcall: res.data.bidcall[i],
            bidput: res.data.bidput[i],
            etfcall: res.data.etfcall[i],
            etfput: res.data.etfput[i],
          });
        }
        return tabdata;
      }
    }
    const {
      aiwatch: { data },
      loading,
      total,
    } = this.props;

    const {
      selectedRows,
      modalVisible,
      updateModalVisible,
      stepFormValues,
      listLoading,
    } = this.state;

    const newdata = {
      list: formatdata(data),
      pagination: {
        current: this.state.formValues.page,
        pageSize: this.state.formValues.pagesize,
        total: parseInt(data.total),
      },
    };

    return (
      <PageHeaderWrapper title="美股期权成交监控列表">
        <div className={styles.controlBar}>
          <div style={{ display: 'flex', flexFlow: 'row wrap' }}>
            <Input
              ref="IDinput"
              className={styles.IDinput}
              placeholder="请输入上传人User ID"
              prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />}
            />
            <Button type="primary" className="optionsbutton" onClick={this.optionsUpload}>
              上传
            </Button>
            <input className={styles.hiddenIpt} id="fileipt" type="file" />
          </div>
          <div style={{ display: 'flex', flexFlow: 'row wrap' }}>
            <div className={styles.resultTag}>{data.message}</div>

            <Button type="primary" icon="sync" onClick={this.pageRefresh}>
              刷新
            </Button>
          </div>
          {/* <Button onClick={this.optionsClear}>清空</Button> */}
        </div>
        <Card bordered={false}>
          <div className={styles.tableList}>
            {/*      <div className={styles.tableListForm}>{this.renderForm()}</div> */}
            <StandardTable
              selectedRows={selectedRows}
              loading={listLoading}
              data={newdata}
              columns={this.columns}
              onChange={this.handleStandardTableChange}
              rowKey="id"
              pagination="false"
              hideOnSinglePage
            />
          </div>
        </Card>
      </PageHeaderWrapper>
    );
  }

  pageRefresh = () => {
    location.reload();
  };

  optionsClear = () => {
    const that = this;
    const { dispatch } = this.props;
    const { formValues } = this.state;
    dispatch({
      type: 'monitor/DelMonitor',
      payload: formValues,
      callback: res => {
        message.success('清空成功!');
      },
    });
  };

  optionsUpload = () => {
    const clearBtn = document.querySelector('.clear_handPanel');

    const that = this;

    document.querySelector('#fileipt').click();
    const $fileipt = document.querySelector('#fileipt');

    // $fileipt.addEventListener('change', uploadExcel);

    if ($fileipt.getAttribute('change') !== '1') {
      $fileipt.setAttribute('change', '1');
      $fileipt.addEventListener('change', uploadExcel);
    }
    function uploadExcel() {
      if (!this.files) {
        return;
      }
      const f = this.files[0];
      $fileipt.value = '';
      parseXLSX(f, function(carData) {
        const { dispatch } = that.props;
        const { formValues } = that.state;
        dispatch({
          type: 'aiwatch/UploadCountTopBottom',
          payload: format(carData),
          callback: res => {
            message.success(res.message);
            if (res.code == 1) {
              localStorage.setItem('markToken', res.data);
              localStorage.setItem('userToken', format(carData).userId);
              that.refs.IDinput.state.value = localStorage.getItem('userToken') || '';
              const { dispatch } = that.props;
              const { formValues } = that.state;
              dispatch({
                type: 'aiwatch/CountTopBottom',
                payload: {
                  mark: localStorage.getItem('markToken') * 1,
                },
                callback: res => {},
              });
            }
          },
        });
      });
      function format(carData) {
        const obj = {};
        const reg = /(\ )|(\")|(\')|(\r)|(\n)|(\,)/g;
        for (let i = 0, len = carData.length; i < len; i++) {
          for (const j in carData[i]) {
            if (!obj[j]) {
              obj[j] = [];
            }
            obj[j].push(carData[i][j].replace(reg, ''));
          }
        }
        obj.userId = that.refs.IDinput.state.value;

        return obj;
      }
      function formatDate(numb) {
        const time = new Date((numb - 1) * 24 * 3600000 + 1);
        time.setYear(time.getFullYear() - 70);
        const year = `${time.getFullYear()}`;
        const month = `${time.getMonth() + 1}`;
        const date = `${time.getDate()}`;

        return `${month < 10 ? `0${month}` : month}月${date < 10 ? `0${date}` : date}日`;
      }
    }

    function parseXLSX(f, cb) {
      let carData;
      let wb; // 读取完成的数据
      const rABS = false; // 是否将文件读取为二进制字符串
      const reader = new FileReader();
      reader.onload = function(e) {
        const data = e.target.result;
        if (rABS) {
          wb = XLSX.read(btoa(fixdata(data)), {
            type: 'base64',
          });
        } else {
          wb = XLSX.read(data, {
            type: 'binary',
          });
        }
        // carData就是我们需要的JSON数据
        carData = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);

        typeof cb === 'function' && cb(carData);
      };
      if (rABS) {
        reader.readAsArrayBuffer(f);
      } else {
        reader.readAsBinaryString(f);
      }
      function fixdata(data) {
        // 文件流转BinaryString
        let o = '';
        let l = 0;
        const w = 10240;
        for (; l < data.byteLength / w; ++l)
          o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w, l * w + w)));
        o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w)));
        return o;
      }
    }
  };

  // 加载完 之后 再加载 此 方法
  // componentWillMount() {
  //   const s = document.createElement('script');
  //   s.type = 'text/javascript';
  //   s.src = '../../assets/xlsx.min.js';
  //   document.body.appendChild(s);
  // }
  componentDidMount() {
    this.refs.IDinput.state.value = localStorage.getItem('userToken') || '';
    const { dispatch } = this.props;
    const { formValues } = this.state;
    dispatch({
      type: 'aiwatch/CountTopBottom',
      payload: {
        mark: localStorage.getItem('markToken'),
      },
      callback: res => {},
    });
  }

  // 改变每页条数和当前页
  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    formValues.page = pagination.current;
    formValues.pagesize = pagination.pageSize;
    const params = {
      ...formValues,
    };
    dispatch({
      type: 'monitor/GetFundTwoList',
      payload: params,
    });
  };

  // 判断 菜单栏 是 缩放显示 还是 全部展示
  renderForm() {
    const { expandForm } = this.state;
    return expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
  }

  // 菜单栏- 点击展开显示 事件
  renderAdvancedForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="最大财报日">
              {getFieldDecorator('maxEarningsDate ')(
                <DatePicker style={{ width: '100%' }} placeholder="请输入最大财报日" />
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="最小财报日">
              {getFieldDecorator('minEarningsDate')(
                <DatePicker style={{ width: '100%' }} placeholder="请输入最小财报日" />
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="最小保本幅度">
              {getFieldDecorator('minBreakEvenMargin')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="最小权利金">
              {getFieldDecorator('minRoyalty')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="最小收益率">
              {getFieldDecorator('minYieldRate')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
        </Row>
        <div style={{ overflow: 'hidden' }}>
          <div style={{ marginBottom: 24 }}>
            <Button type="primary" htmlType="submit">
              查询
            </Button>
            <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
              重置
            </Button>
            <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
              收起 <Icon type="up" />
            </a>
          </div>
        </div>
      </Form>
    );
  }

  // 菜单栏 默认收缩显示 事件
  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="最小权利金">
              {getFieldDecorator('minRoyalty')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="最小收益率">
              {getFieldDecorator('minYieldRate')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
              <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                展开 <Icon type="down" />
              </a>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  // 菜单栏-查询按钮 事件
  handleSearch = e => {
    e.preventDefault();
    const { dispatch, form } = this.props;
    const { formValues } = this.state;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
      };
      if (values.maxEarningsDate != undefined) {
        formValues.maxEarningsDate = values.maxEarningsDate;
      }
      if (values.minBreakEvenMargin != undefined) {
        formValues.minBreakEvenMargin = parseFloat(values.minBreakEvenMargin);
      }
      if (values.minEarningsDate != undefined) {
        formValues.minEarningsDate = values.minEarningsDate;
      }
      if (values.minRoyalty != undefined) {
        formValues.minRoyalty = parseFloat(values.minRoyalty);
      }
      if (values.minYieldRate != undefined) {
        formValues.minYieldRate = parseFloat(values.minYieldRate);
      }
    });

    dispatch({
      type: 'monitor/GetRoyaltiesList',
      payload: formValues,
    });
  };

  // 菜单栏- 重置按钮 事件
  handleFormReset = () => {
    const { form, dispatch } = this.props;
    const { formValues } = this.state;
    form.resetFields();
    formValues.maxEarningsDate = '';
    formValues.minBreakEvenMargin = 0;
    formValues.minEarningsDate = '';
    formValues.minRoyalty = 0;
    formValues.minYieldRate = 0;

    dispatch({
      type: 'monitor/GetRoyaltiesList',
      payload: formValues,
    });
  };

  // 菜单栏- 展开 关闭 事件
  toggleForm = () => {
    const { expandForm } = this.state;
    this.setState({
      expandForm: !expandForm,
    });
  };
}
function mul(arg1, arg2) {
  let m = 0;
  const s1 = arg1.toString();
  const s2 = arg2.toString();
  try {
    m += s1.split('.')[1].length;
  } catch (e) {}
  try {
    m += s2.split('.')[1].length;
  } catch (e) {}
  return (Number(s1.replace('.', '')) * Number(s2.replace('.', ''))) / Math.pow(10, m);
}
export default TwoFundPosition;
